package com.team_project.boot.controller;

import com.team_project.boot.entity.Product;
import com.team_project.boot.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Controller
@RestController
public class ProductController {
    @Autowired(required = false)
    ProductMapper mapper;
    @RequestMapping("/selectCategory")
    public List<Product> selectAll(){
        return mapper.selectAll();
    }

    @Value("${imagePath}")
    private String imagePath;
    @RequestMapping("/addCategory")
    public void addCategory(Product product, MultipartFile file){
        String fileName = file.getOriginalFilename();
        String suixx = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suixx;
        SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");

        /*创建表示当前时间的日期对象*/
        Date date = new Date();
        //得到日期路径
        String datePath = f.format(date);
        String path = imagePath+datePath;
        File dir = new File(path+fileName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(path+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String content = product.getText().substring(0,10)+"...";
        product.setContent(content);
        product.setPicurl(datePath+fileName);
        mapper.insert(product);
    }
}
